package com.orange.core.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.core.pojo.R;
import com.orange.core.pojo.enums.EErrorCode;
import com.orange.core.util.Constants;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@AllArgsConstructor
public class AccountAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) {
        if (!response.isCommitted()) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            log.warn("当前账号 {} 访问被禁止：{}", authentication.getName(), accessDeniedException.getMessage());
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON_UTF8_VALUE);
            PrintWriter writer = response.getWriter();
            writer.write(objectMapper.writeValueAsString(R.fail(EErrorCode.ACCESS_FORBIDDEN)));
        }
    }
}
